package com.oocl.servlet;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.oocl.exception.MyException;
import com.oocl.pojo.Orders;
import com.oocl.service.OrdersService;
import com.oocl.service.impl.OrdersServiceFactory;
import com.oocl.service.impl.ServiceFactory;


public class PurchaserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Map<String, Integer> cart = (Map<String, Integer>) request.getSession()
				.getAttribute("cart");
		String pId = (String) request.getSession().getAttribute("pId");
		List<Orders> list = new ArrayList<Orders>();
		Set<String> set = cart.keySet();
		Date date = new Date();
		for (String bId : set) {
			Orders o = new Orders();
			String oId = UUID.randomUUID().toString();
			o.setId(oId);
			o.setbId(bId);
			o.setbDate(date);
			o.setpId(pId);
			o.setCount(cart.get(bId));
			list.add(o);
		}
		try {
			OrdersServiceFactory factory = (OrdersServiceFactory) ServiceFactory
					.getServiceFactory(OrdersServiceFactory.ORDERS);
			OrdersService oSer = factory.getService();
			oSer.addOrders(list);
			request.getSession().setAttribute("cart", null);
			request.setAttribute("pId", pId);
			request.setAttribute("date", date);
			request.setAttribute("list", list);
			request.getRequestDispatcher("orders.jsp").forward(request, response);
		} catch (MyException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}
